# test.py
import asyncio
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain_deepseek import ChatDeepSeek

DEEPSEEK_API_KEY = "sk-2f1767eebb5749adb135e7f93912a313"

# 初始化DeepSeek模型
llm = ChatDeepSeek(
    model="deepseek-chat",
    temperature=0.7,
    api_key=DEEPSEEK_API_KEY,
    request_timeout=30
)

async def main():
    # 初始化MCP客户端
    client = MultiServerMCPClient(
        {
            "tools": {
                "url": "http://localhost:8000/mcp",
                "transport": "streamable_http",
            }
        }
    )

    # 异步获取工具（注意使用await）
    tools = await client.get_tools()
    print(f"成功获取 {len(tools)} 个工具")

    tool_map = {tool.name: tool for tool in tools}

    # 打印工具信息
    for tool in tools:
        print(f"工具名称: {tool.name}")
        print(f"工具描述: {tool.description}")

    # 创建agent
    tool_llm = llm.bind_tools(tools=tools)

    url = "https://langchain-ai.github.io/langgraph/agents/mcp/#use-mcp-tools"
    # 执行agent
    response = tool_llm.invoke(
        f"帮我打开这个网址:{url}"
    )

    print("工具调用响应:", response)

    # 第二步：检查并执行工具调用
    if hasattr(response, 'tool_calls') and response.tool_calls:
        print("模型决定调用工具:")
        tool_calls = response.tool_calls  # 这里是个数组，模型首先返回决定调用的工具列表
        print("tool_calls", tool_calls)

        # 实际执行工具调用
        for i, tool_call in enumerate(tool_calls):
            tool_name = tool_call['name']
            print(f"执行工具 {i + 1}: {tool_name}")

            # 关键步骤：实际调用工具
            if tool_name in tool_map:
                # 这里才是真正执行工具的地方
                tool_result = await tool_map[tool_name].ainvoke(tool_call)
                print(f"✅ 工具执行成功: {tool_result}")
            else:
                print(f"❌ 未找到工具: {tool_name}")
    else:
        print("模型没有调用工具，直接返回答案")
        print("回答内容:", response.content)
# 运行异步函数
if __name__ == "__main__":
    asyncio.run(main())